import base64
import json
import random
import time
import hashlib
import requests

from django.shortcuts import render, HttpResponse, redirect
from api.models import User
from lxml import etree


class HaiJiaoSheQuSpider:
    def __init__(self):
        self.__Domain = "https://www.hj87d29.top"
        self.__headers = {
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'access-control-allow-credentials': 'true',
            # 'cookie': '_ga=GA1.1.1751858735.1713072267; _ga_H4G4E5X3FL=GS1.1.1713072267.1.1.1713072508.0.0.0',
            'mver': '211112203214',
            'referer': 'https://www.hj87d29.top/home',
            'sec-ch-ua': '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
            'sec-ch-ua-mobile': '?1',
            'sec-ch-ua-platform': '"Android"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Mobile Safari/537.36',
            'x-user-id': '171308205701',
            'x-user-token': '14d282739b2f412e8178a92fed57988b',
        }

    # 海角加密破解函数
    @staticmethod
    def __HaiJiaoJieMa(JMFN=None) -> dict:
        base64_encoded_string = JMFN
        if base64_encoded_string is None:
            return {"data": None}
            pass
        for i in range(3):
            base64_encoded_string = base64.b64decode(base64_encoded_string)
        # 将解码后的字节对象转换为字符串
        # decoded_string = base64_encoded_string.decode("utf-8")
        return json.loads(base64_encoded_string)

    # 自动转换成数据
    def __DefaultInfo(self, JsonData):
        if JsonData is None:
            return []
        response = self.__HaiJiaoJieMa(JMFN=JsonData['data'])
        return response

    # 获取热帖新闻
    def GetHot(self, Page):
        SpiderUrl = self.__Domain + "/api/topic/hot/topics"
        params = {
            "page": Page
        }
        response = self.__DefaultInfo(requests.get(url=SpiderUrl, headers=self.__headers, params=params).json())
        return response

    # 获取帖子的消息
    def GetPostsInfo(self, TopicId):
        SpiderUrl = self.__Domain + f"/api/topic/{TopicId}"
        response = self.__DefaultInfo(requests.get(url=SpiderUrl, headers=self.__headers).json())
        return response

    # 获取帖子的评论
    def GetPostsCommentsInfo(self, topic_id, page):
        SpiderUrl = self.__Domain + f"/api/comment/reply_list"
        params = {
            "page": page,
            "sort": "asc",
            "topic_id": topic_id,
            "search_type": 0,
            "user_id": 0
        }
        response = self.__DefaultInfo(requests.get(url=SpiderUrl, headers=self.__headers, params=params).json())
        return response

    # 获取视频
    def GetPostsVideo(self, VideoID, resource_id):
        SpiderUrl = self.__Domain + "/api/attachment"
        jsdata = {
            "id": VideoID,
            "resource_id": resource_id,
            "line": "",
            "resource_type": "topic"
        }
        response = self.__HaiJiaoJieMa(requests.post(url=SpiderUrl, headers=self.__headers, json=jsdata).json()['data'])
        Result = {
            "VideoUrl": self.__Domain + response['remoteUrl'],
            "coverUrl": response['coverUrl']
        }
        return Result

    # 返回搜索热门栏目
    def GetSearchHotInfo(self):
        SpiderUrl = self.__Domain + "/api/ranking/search_words"
        response = self.__DefaultInfo(requests.get(url=SpiderUrl, headers=self.__headers).json())
        return response

    # 搜索
    def GetSearchInfo(self, key, page):
        SpiderUrl = self.__Domain + "/api/topic/search"
        jsdata = {
            "key": key,
            "node_id": 0,
            "page": page
        }
        response = self.__DefaultInfo(requests.post(url=SpiderUrl, headers=self.__headers, json=jsdata).json())
        return response

    # UA池
    def get_ua(self) -> dict:
        user_agents = [
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60',
            'Opera/8.0 (Windows NT 5.1; U; en)',
            'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50',
            'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50',
            'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',
            'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2 ',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
            'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36',
            'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',
            'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)',
            'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0',
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0) ',
        ]
        user_agent = random.choice(user_agents)  # random.choice(),从列表中随机抽取一个对象
        headers = {'User-Agent': user_agent}
        return headers

    # 点赞
    def dianzhan(self, TzID, token, user_id):
        url = self.__Domain + f"/api/topic/like/{TzID}"
        params = self.get_ua()
        params['X-User-Id'] = user_id
        params['X-User-Token'] = token
        res = requests.post(url, headers=params).json()
        dat = res['data']
        if dat is None:
            dat = res['message']
            return dat

        return self.__HaiJiaoJieMa(dat)

    # 活跃账号
    def huoyzhanghao1(self, User_Name, User_Password):
        url = self.__Domain + "/api/login/signin"
        UA = self.get_ua()['User-Agent']
        header = {
            'User-Agent': UA
        }
        input_string = User_Name + User_Password + UA
        hashZHI = hashlib.md5(input_string.encode()).hexdigest()
        Params = {
            "captchaCode": "",
            "captchaId": "",
            "password": User_Password,
            "ref": "/",
            "sign": hashZHI,
            "username": User_Name
        }
        response = requests.post(url, headers=header, json=Params).json()

        if response['isEncrypted']:
            res = self.__HaiJiaoJieMa(response['data'])
            return True, res['token']
        return False, "123456789"

    # 关注
    def guanzhu(self, UserID, UserToken, TzID, AD):
        SpiderUrl = self.__Domain + "/api/user/favorite"
        headers = {
            'User-Agent': self.get_ua()['User-Agent'],
            'x-user-id': UserID,
            'x-user-token': UserToken,
        }
        if AD:
            Params = {
                "targetId": TzID,
                "opt": "add"
            }
        else:
            Params = {
                "targetId": TzID,
                "opt": "rm"
            }
        response = requests.get(url=SpiderUrl, headers=headers, params=Params).json()
        if response['success']:
            return True
        else:
            return False

    # 获取金币
    def GetJinBi(self, UserID, UserToken):
        SpiderUrl = self.__Domain + "/api/user/user_sign_in"
        Params = {
            "User-Agent": self.get_ua()['User-Agent'],
            'x-user-id': UserID,
            'x-user-token': UserToken
        }
        res = requests.post(SpiderUrl, headers=Params).json()
        if res['success']:
            return True
        else:
            return False

    # 登录-取消息
    def LoginInfo(self, UserName, UserPwd):
        SpiderUrl = self.__Domain + "/api/login/signin"
        UA = self.get_ua()['User-Agent']
        Tring = UserName + UserPwd + UA
        hashZHI = hashlib.md5(Tring.encode()).hexdigest()
        Params = {
            "captchaCode": "",
            "captchaId": "",
            "password": UserPwd,
            "ref": "/",
            "sign": hashZHI,
            "username": UserName
        }
        res = requests.post(url=SpiderUrl, headers={"User-Agent": UA}, json=Params).json()
        if res['success']:
            return {
                "success": True,
                "data": self.__DefaultInfo(res)
            }
        else:
            return {
                "success": False,
                "data": res['message']
            }

    # 数据采集 - 热门爆料
    def ReMenBaoLiao(self, domain, nid):

        html_text = requests.get(domain + f"/archives/{nid}/", headers=self.get_ua()).text
        etree_text = etree.HTML(html_text)
        html_content = etree_text.xpath('//*[@class="post-content"]')[0]
        result = etree.tostring(html_content, encoding='utf-8').decode()
        return result


sp = HaiJiaoSheQuSpider()

NavLeft = [
    {"title": "主号", "url": "/user/boos/", "IsItem": False, "ItemList": []},
    {"title": "海角账号", "url": "/index/", "IsItem": False, "ItemList": []},
    {"title": "功能区", "url": "javascript:;", "IsItem": True, "ItemList": [
        {"title": "批量点赞", "url": "/Batchlike/"},
        {"title": "批量关注", "url": "/GuanZhu/"},
        {"title": "数据采集", "url": "/Shujucaiji/"},
    ]},
]

Resurl = {
    "NavLeft": NavLeft
}


# 主号
def Boos(request):
    if request.method == "GET":
        return render(request, 'data.html', Resurl)
    elif request.method == "POST":
        UserName = request.POST.get("UserName")
        UserPwd = request.POST.get("UserPwd")
        res = sp.LoginInfo(UserName=UserName, UserPwd=UserPwd)
        return HttpResponse(json.dumps(res))


# 首页文件
def index(request):
    # 读取全部用户
    userAll = User.objects.all()
    if request.method == "GET":
        Uresponse = {
            "userAll": userAll
        }
        Resurl.update(Uresponse)
        return render(request, 'index.html', Resurl)
    elif request.method == "POST":
        """
            type == 1 为活跃账号
        """
        Type = request.POST.get("Type")
        if Type == "1":
            # 活跃账号
            for user in userAll:
                user_name = user.user_name
                user_password = "qwe12345"
                res, TOKEN = sp.huoyzhanghao1(User_Name=user_name, User_Password=user_password)
                if res:
                    row_obj = User.objects.filter(user_id=user.user_id).first()
                    row_obj.is_active = "已活跃"
                    row_obj.token = TOKEN
                    row_obj.save()
                    # continue

            return HttpResponse("活动完成, 可能有登录失败的僵尸, 可重新进行活跃")
        elif Type == "2":
            num = 0
            for user in userAll:
                user_id = user.user_id
                user_token = user.token
                res = sp.GetJinBi(UserToken=user_token, UserID=user_id)
                if res == True:
                    num += 1
            return HttpResponse(
                f"感谢您为僵尸账号做出的贡献, 愿它们未来可以帮助到屏幕前的您! 本次领取金币成功者: {num}")
        return HttpResponse("false")


# 脚本区: 点赞
def dianzhan(request):
    if request.method == "GET":
        return render(request, 'Batchlike.html', Resurl)
    elif request.method == "POST":
        data = request.POST
        PostsID = data['PostsID']
        # 向服务器查询数据
        UserList = User.objects.all()
        ResulrJSONList = []
        for obj in UserList:
            UserID = obj.user_id
            UserToken = obj.token
            res = sp.dianzhan(TzID=PostsID, token=UserToken, user_id=UserID)
            Ri = {
                "UserName": obj.user_name,
                "UserID": UserID,
                "res": res
            }
            ResulrJSONList.append(Ri)
        return HttpResponse(json.dumps(ResulrJSONList))


def guanzhu(request):
    if request.method == "GET":
        return render(request, 'GuanZhu.html', Resurl)
    elif request.method == "POST":
        MBID = request.POST['id']
        AD = request.POST['isG']
        GuanL = 0  # 关注的人数
        for obj in User.objects.all():
            UserID = obj.user_id
            # R, TOKEN = sp.huoyzhanghao1(User_Name=obj.user_name, User_Password='qwe12345')
            TOKEN = obj.token
            Tzid = MBID
            if AD == "op":
                # 关注
                res = sp.guanzhu(UserID, TOKEN, TzID=Tzid, AD=True)
            else:
                # 取消关注
                res = sp.guanzhu(UserID, TOKEN, TzID=Tzid, AD=False)

            if res:
                GuanL += 1
            else:
                continue
        return HttpResponse(json.dumps({"result": True, "umber": GuanL}))


# 数据采集
def ShuJuCaiJi(request):
    if request.method == "GET":
        Params = {
            "list": [
                {"id": 1, "name": "热门爆料", "url": "https://hye5z2.umugygaex.com/category/rsbl/"}
            ],
        }
        Resurl.update(Params)
        return render(request, '数据采集.html', Resurl)
    elif request.method == "POST":
        try:
            NID = request.POST['nid']
            domain = "https://hye5z2.umugygaex.com"
            res_text = sp.ReMenBaoLiao(domain=domain, nid=NID)
            return HttpResponse(res_text, content_type="text/plain", status=200)
        except Exception as e:
            return HttpResponse("采集失敗", status=502)
        # 获取用户ip地址
    return HttpResponse("非法提交", content_type="text/plain", status=200)

# 數據采集 - 選擇項目
def shuju_option(request):
    if request.method == "GET":
        Type = request.GET.get("type")
        if Type == "" or Type is None:
            return HttpResponse("請你携帶正確的參數")
        params = {
            "1": "https://hye5z2.umugygaex.com/category/rsbl/"
        }
        return HttpResponse(params[Type])